package com.zhehekeji.opsys.api.plugin.wechat.service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhehekeji.opsys.api.cache.WechatCache;
import com.zhehekeji.opsys.api.conf.Config;
import com.zhehekeji.opsys.api.entity.TWechatConfig;
import com.zhehekeji.opsys.api.plugin.wechat.code.WechatResultCode;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.QrcodeShowRsp;
import com.zhehekeji.opsys.api.plugin.wechat.util.FileUtils;
import com.zhehekeji.opsys.api.plugin.wechat.util.HttpUtils;
import com.zhehekeji.opsys.api.util.UUIDUtils;

import net.sf.json.JSONObject;

/**
 * @ClassName WechatCustomProxyManagerService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2018-3-24   下午3:20:33
 */
@Service
public class WechatCustomProxyManagerService {
	
	private static final Logger logger = LoggerFactory.getLogger(WechatCustomProxyManagerService.class);
	
	@Autowired
	private WechatCache wechatCache;
	@Autowired
	private Config config;
	
	public QrcodeShowRsp getQrcodeShow(String activityCode, String userID, int amount, int limitTimes, int limitCycle) {
		QrcodeShowRsp rsp = new QrcodeShowRsp();
		String resultDesc = "获取二维码成功！";
		try{
			String tmpWechatPictureStoreAddress = config.getWechatPictureStoreAddress();
			if (StringUtils.isBlank(tmpWechatPictureStoreAddress)) {
				resultDesc = "获取二维码失败，微信图片本地存放地址不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_PICTURE_STORE_ADDRESS_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpWechatPictureVisitAddress = config.getWechatPictureVisitAddress();
			if (StringUtils.isBlank(tmpWechatPictureVisitAddress)) {
				resultDesc = "获取二维码失败，微信图片访问地址不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_PICTURE_VISIT_ADDRESS_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			TWechatConfig tmpTWechatConfig = wechatCache.getWechatConfig();
			if (tmpTWechatConfig == null) {
				resultDesc = "获取二维码失败，微信配置不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_CONFIG_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpQrcodeInterfaceUrl = tmpTWechatConfig.getQrcodeInterfaceUrl();
			if (StringUtils.isBlank(tmpQrcodeInterfaceUrl)) {
				resultDesc = "获取二维码失败，二维码访问接口URL！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.QRCODE_INTERFACE_URL_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			StringBuilder urlBuilder = new StringBuilder(tmpQrcodeInterfaceUrl);
			if (tmpQrcodeInterfaceUrl.indexOf("?") != -1) {
				urlBuilder.append("&");
			} else {
				urlBuilder.append("?");
			}
			if (activityCode == null) {
				activityCode = "";
			}
			if (userID == null) {
				userID = "";
			}
			urlBuilder.append("activityCode=").append(activityCode)
			.append("&userID=").append(userID)
			.append("&amount=").append(amount)
			.append("&limitTimes=").append(limitTimes)
			.append("&limitCycle=").append(limitCycle);
			String rspBody = null;
			try {
				rspBody = HttpUtils.get(urlBuilder.toString());
			} catch (IOException e) {
				resultDesc = "获取二维码失败，调用二维码访问接口URL失败！";
				logger.error(resultDesc, e);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			if (StringUtils.isBlank(rspBody)){
				resultDesc = "获取二维码失败，调用二维码访问接口URL失败，返回数据为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			JSONObject tmpJSONObject = JSONObject.fromObject(rspBody);
			Object tmpObject = tmpJSONObject.get("qrcodeShowRsp");
			if (tmpObject != null) {
				rsp = (QrcodeShowRsp) JSONObject.toBean(JSONObject.fromObject(tmpObject), QrcodeShowRsp.class);
			} else {
				rsp = (QrcodeShowRsp) JSONObject.toBean(tmpJSONObject, QrcodeShowRsp.class);
			}
			if (rsp == null) {
				rsp = new QrcodeShowRsp();
				resultDesc = "获取二维码失败，调用二维码访问接口URL失败，返回数据为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			if (rsp.getResultCode() != WechatResultCode.SUCCESS) {
				return rsp;
			}
			String tmpQrcodeVisitUrl = rsp.getUrl();
			if (StringUtils.isBlank(tmpQrcodeVisitUrl)) {
				resultDesc = "获取二维码失败，返回的微信二维码url为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String fileRelativeDir = "1001" + File.separator + "wechatqrcode";
			String fileName = UUIDUtils.randomUUID() + ".jpg";
			String fileStoreDir = tmpWechatPictureStoreAddress + File.separator + fileRelativeDir;
			File file = new File(fileStoreDir);
			if (!file.exists()){
				file.mkdirs();
			}
			String destPath = fileStoreDir + File.separator + fileName;
			try {
				FileUtils.download(tmpQrcodeVisitUrl, destPath);
			} catch (Exception e) {
				resultDesc = "获取二维码失败，二维码本地存储失败！";
				logger.error(resultDesc, e);	
				rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpQrcode = fileRelativeDir + File.separator + fileName;
			String httpPath = tmpWechatPictureVisitAddress + File.separator + tmpQrcode;
			rsp.setUrl(httpPath);
			logger.info(resultDesc);
		}catch (Exception e){
			resultDesc = "获取二维码失败，程序异常！";
			logger.error(resultDesc, e);
			rsp.setResultCode(WechatResultCode.APPLICATION_EXCEPTION);
			rsp.setResultDesc(resultDesc);
		}
		return rsp;
	}
	
	public QrcodeShowRsp getSafeQrcodeShow(String sign) { 
		QrcodeShowRsp rsp = new QrcodeShowRsp();
		String resultDesc = "获取二维码成功！";
		try{
			String tmpWechatPictureStoreAddress = config.getWechatPictureStoreAddress();
			if (StringUtils.isBlank(tmpWechatPictureStoreAddress)) {
				resultDesc = "获取二维码失败，微信图片本地存放地址不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_PICTURE_STORE_ADDRESS_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpWechatPictureVisitAddress = config.getWechatPictureVisitAddress();
			if (StringUtils.isBlank(tmpWechatPictureVisitAddress)) {
				resultDesc = "获取二维码失败，微信图片访问地址不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_PICTURE_VISIT_ADDRESS_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			TWechatConfig tmpTWechatConfig = wechatCache.getWechatConfig();
			if (tmpTWechatConfig == null) {
				resultDesc = "获取二维码失败，微信配置不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.WECHAT_CONFIG_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpQrcodeInterfaceSafeUrl = tmpTWechatConfig.getQrcodeInterfaceSafeUrl();
			if (StringUtils.isBlank(tmpQrcodeInterfaceSafeUrl)) {
				resultDesc = "获取二维码失败，二维码访问加密接口URL！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.QRCODE_INTERFACE_URL_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			StringBuilder urlBuilder = new StringBuilder(tmpQrcodeInterfaceSafeUrl);
			if (tmpQrcodeInterfaceSafeUrl.indexOf("?") != -1) {
				urlBuilder.append("&");
			} else {
				urlBuilder.append("?");
			}
			if (sign == null) {
				sign = "";
			}
			urlBuilder.append("sign=").append(sign);
			String rspBody = null;
			try {
				rspBody = HttpUtils.get(urlBuilder.toString());
			} catch (IOException e) {
				resultDesc = "获取二维码失败，调用二维码访问加密接口URL失败！";
				logger.error(resultDesc, e);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			if (StringUtils.isBlank(rspBody)){
				resultDesc = "获取二维码失败，调用二维码访问加密接口URL失败，返回数据为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			JSONObject tmpJSONObject = JSONObject.fromObject(rspBody);
			Object tmpObject = tmpJSONObject.get("qrcodeShowRsp");
			if (tmpObject != null) {
				rsp = (QrcodeShowRsp) JSONObject.toBean(JSONObject.fromObject(tmpObject), QrcodeShowRsp.class);
			} else {
				rsp = (QrcodeShowRsp) JSONObject.toBean(tmpJSONObject, QrcodeShowRsp.class);
			}
			if (rsp == null) {
				rsp = new QrcodeShowRsp();
				resultDesc = "获取二维码失败，调用二维码访问加密接口URL失败，返回数据为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			if (rsp.getResultCode() != WechatResultCode.SUCCESS) {
				return rsp;
			}
			String tmpQrcodeVisitUrl = rsp.getUrl();
			if (StringUtils.isBlank(tmpQrcodeVisitUrl)) {
				resultDesc = "获取二维码失败，返回的微信二维码url为空！";
				logger.error(resultDesc);	
				rsp.setResultCode(WechatResultCode.CALL_QRCODE_INTERFACE_URL_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String fileRelativeDir = "1001" + File.separator + "wechatqrcode";
			String fileName = UUIDUtils.randomUUID() + ".jpg";
			String fileStoreDir = tmpWechatPictureStoreAddress + File.separator + fileRelativeDir;
			File file = new File(fileStoreDir);
			if (!file.exists()){
				file.mkdirs();
			}
			String destPath = fileStoreDir + File.separator + fileName;
			try {
				FileUtils.download(tmpQrcodeVisitUrl, destPath);
			} catch (Exception e) {
				resultDesc = "获取二维码失败，二维码本地存储失败！";
				logger.error(resultDesc, e);	
				rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			String tmpQrcode = fileRelativeDir + File.separator + fileName;
			String httpPath = tmpWechatPictureVisitAddress + File.separator + tmpQrcode;
			rsp.setUrl(httpPath);
			logger.info(resultDesc);
		}catch (Exception e){
			resultDesc = "获取二维码失败，程序异常！";
			logger.error(resultDesc, e);
			rsp.setResultCode(WechatResultCode.APPLICATION_EXCEPTION);
			rsp.setResultDesc(resultDesc);
		}
		return rsp;
	}
}

